package cn.com.dycc.sys_manage.rolesysmanagement.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.sys_manage.menusysmanagement.dao.MenuDao;
import cn.com.dycc.sys_manage.menusysmanagement.entity.Menu;
import cn.com.dycc.sys_manage.menusysmanagement.service.MenuNotFoundException;
import cn.com.dycc.sys_manage.rolesysmanagement.dao.RoleDao;
import cn.com.dycc.sys_manage.rolesysmanagement.dao.RoleMenuDao;
import cn.com.dycc.sys_manage.rolesysmanagement.dao.RoleUserDao;
import cn.com.dycc.sys_manage.rolesysmanagement.entity.Role;
import cn.com.dycc.sys_manage.rolesysmanagement.entity.RoleResult;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.IntegerUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * Description: 角色-菜单权限业务处理层
 * Author: linfangan
 * Version: 1.0
 * Create Date Time: 2017年8月8日 下午5:10:54.
 * Update Date Time: 
 * @see
 */
@Service("roleMenuService")
@Transactional
public class RoleMenuServiceImpl implements RoleMenuService{
	
	@Resource(name="roleDao")
	private RoleDao roleDao;
	
	@Resource(name="roleMenuDao")
	private RoleMenuDao roleMenuDao;
	
	@Resource(name="menuDao")
	private MenuDao menuDao;
	
	@Resource(name="roleUserDao")
	private RoleUserDao roleUserDao;
	
	//新增角色和管理角色菜单权限
	@SystemServiceLog(description=Constants.T_ROLEMENU_ADD)
	public Map<String,Object> addRoleMenu(Role role,String[] privIds) 
			throws RoleMenuNotFoundException,MenuNotFoundException,RoleNotFoundException {
		
		//登录用户id
		String opt_user_id = role.getOpt_user_id();
		if(opt_user_id==null){
			throw new RoleNotFoundException("请登录！");
		}
		String roleNo = role.getRole_no();
		if(roleNo==null){
			throw new RoleNotFoundException("角色编号不能为空!");
		}
		//判断为整型
		boolean b = IntegerUtil.isNumeric(roleNo);
		if(b==false){
			throw new RoleNotFoundException("角色编号请填写为整型!");
		}
		String roleName = role.getRole_name();
		Integer orderNo = role.getOrder_no();
		if(roleName==null||roleName.trim().isEmpty()){
			throw new RoleNotFoundException("角色名称不能为空");
		}
		//组织标识
		String org_id = role.getOrg_id();
		
		//是否启用
		String state = role.getState();
		if(state==null){
			role.setState("Y");
		}
		RoleResult sel_roleno = roleDao.findRoleByRoleNo(roleNo,org_id);
		if(sel_roleno!=null){
			throw new RoleNotFoundException("角色编号已被使用");
		}
		Role sel_rolename = roleDao.findRoleByRoleName(roleName,org_id);
		if(sel_rolename!=null){
			throw new RoleNotFoundException("角色名称已被使用");
		}
		Role aRole = new Role();
		if(orderNo==null){
			aRole.setOrder_no(orderNo);
		}		
		aRole.setRole_no(roleNo);
		aRole.setRole_name(roleName);
		aRole.setOrder_no(orderNo);
		aRole.setOpt_user_id(opt_user_id);
		aRole.setOrg_id(org_id);
//		aRole.setUpdate_user_id(opt_user_id);
		//更新时间
//		String format = "yyyy-MM-dd HH:mm:ss";
//		String update_date = DateUtil.getNowDate(format);
//		aRole.setUpdate_date(update_date);
		int addRole = roleDao.addRole(aRole);
		if(addRole<=0){
			throw new RoleNotFoundException("增加失败！");
		}
		if(privIds.length==0){
			throw new MenuNotFoundException("请选择角色拥有的菜单权限！");
		}
		//循环判断是否选中了菜单
		for(int i = 0;i<privIds.length;i++){
			Menu menu = menuDao.findMenuByMenuNo(privIds[i]);
			if(menu==null){
				throw new MenuNotFoundException("菜单选择错误！");
			}
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("RoleNo",roleNo);
		map.put("privIds",privIds);
		int addRoleMenu = roleMenuDao.addRoleMenu(map);
		
		if(addRoleMenu==privIds.length){
			List<Map<String,Object>> list = roleMenuDao.findMenNoByRoleNo(roleNo);
			//动态数组接收查询返回的菜单id
			ArrayList<String> al=new ArrayList<String>();
			for(int i=0;i < list.size() ;i++){
				String oldMenuNo = list.get(i).get("menu_no").toString();
				al.add(oldMenuNo);
			}
			map.put("privIds",al);
			return map;
		}else{
			throw new RoleNotFoundException("增加失败！");
		}
	}
	
	//修改角色信息和角色的权限管理
	@SystemServiceLog(description=Constants.T_ROLEMENU_UPDATE)
	public Map<String, Object> revampRoleMenu(Role role, String[] privIds)
			throws RoleMenuNotFoundException, MenuNotFoundException,RoleNotFoundException {
		//更新人id
		String update_user_id = role.getUpdate_user_id();
		if(update_user_id==null){
			throw new RoleNotFoundException("请登录！");
		}
		//更新人组织
		String org_id = role.getOrg_id();
		
		//更新角色
		String role_no = role.getRole_no();
		if(role_no==null){
			throw new RoleNotFoundException("角色编号不能改动");
		}
//		int delRole = roleDao.deleteRoleByRoleNo(role_no);
//		if(delRole==0){
//			throw new RoleNotFoundException("角色更新失败！");
//		}
		//对比更新角色名称，先判断是否做了更改
		RoleResult ro = roleDao.findRoleByRoleNo(role_no,org_id);
		String ro_name = ro.getRole_name();
		String role_name = role.getRole_name();
		if(role_name==null||role_name.trim().isEmpty()){
			throw new RoleNotFoundException("角色名称不能为空");
		}
//		System.out.println("菜单更新123456");
		if(!ro_name.equals(role_name)){
			Role sel_RoleName = roleDao.findRoleByRoleName(role_name,org_id);
			if(sel_RoleName!=null){
				throw new RoleNotFoundException("角色名称已被使用");
			}
		}
		Integer order_no = role.getOrder_no();
		//是否启用
		String state = role.getState();
		Role r = new Role();
		if(order_no==null){
			r.setOrder_no(null);
		}
		r.setRole_no(role_no);
		r.setRole_name(role_name);
		r.setOrder_no(order_no);
		if(state==null){
			r.setState("Y");
		}
		r.setUpdate_user_id(update_user_id);
		r.setOrg_id(org_id);
		//更新时间
		String format = "yyyy-MM-dd HH:mm:ss";
		String update_date = DateUtil.getNowDate(format);
		r.setUpdate_date(update_date);
//		int updateRole = roleDao.updateRole(role);
		int updaterole = roleDao.updateRole(r);
		if(updaterole==0){
			throw new MenuNotFoundException("角色更新失败！");
		}
//		System.out.println("菜单更新1234");
		//菜单权限修改
//		System.out.println("role="+role_no);
		List<Map<String,Object>> list = roleMenuDao.findMenNoByRoleNo(role_no);
//		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//		System.out.println(list);
		Map<String,Object> map = new HashMap<String,Object>();
//		int oldMenuNoSize = list.size();
//		System.out.println(oldMenuNoSize);
		//动态数组接收查询返回的值
		ArrayList<String> al=new ArrayList<String>();
		int del = 0;
		if(!(list.isEmpty())){
			for(int i=0;i < list.size() ;i++){
				String oldMenuNo = list.get(i).get("menu_no").toString();
				al.add(oldMenuNo);
			}
			map.put("privIds",al);
			map.put("RoleNo",role_no);
			del = roleMenuDao.deleteRoleMenuByMenuNos(map);
		}
		int add = 0;
		if(privIds.length==0){
			throw new MenuNotFoundException("请选择角色拥有的菜单权限！");
		}
		if(del==list.size()){
			map.put("privIds",privIds);
			map.put("RoleNo",role_no);
			add = roleMenuDao.addRoleMenu(map);
		}
		if(add==privIds.length){
			list = roleMenuDao.findMenNoByRoleNo(role_no);
			al.clear();
			for(int i=0;i < list.size() ;i++){
				String updateMenuNo = 
						list.get(i).get("menu_no").toString();
				al.add(updateMenuNo);
			}
			map.put("privIds",al);
			return map;
		}else{
			throw new RoleNotFoundException("更新失败！");
		}
	}
	
	//查找用户角色权限,包括未选中的，用于增加和修改用户的权限
	public String findMenNoByRoleNo(String role_no,String sys_flag,String org_id) throws RoleMenuNotFoundException,MenuNotFoundException ,RoleNotFoundException{
		
		if(role_no==null){
			throw new RoleNotFoundException("角色编号为空！");
		}
		JSONArray array = new JSONArray();
//		System.out.println(role_no);
		List<Map<String,Object>> listMenuNo = roleMenuDao.findMenNoByRoleNo(role_no);
//		System.out.println(listMenuNo);
		List<Map<String,Object>> listPartMenu = menuDao.findPartMenu(sys_flag,org_id);
		//增加open：true
		for(int i = 0;i<listPartMenu.size();i++){
			String aloneMenuNo = listPartMenu.get(i).get("id").toString();
			for(int j = 0; j<listPartMenu.size();j++){
				String alonePid = listPartMenu.get(j).get("pId").toString();
				if(alonePid.equals(aloneMenuNo)){
					listPartMenu.get(i).put("open","true");
					break;
				}
			}
		}
//		System.out.println(listPartMenu.size());
		if(listMenuNo.isEmpty()){
			for(int i=0;i<listPartMenu.size();i++){
				JSONObject obj = new JSONObject();
				String name = (String) listPartMenu.get(i).get("name");
				Object pId = (Object) listPartMenu.get(i).get("pId");
				Object id = (Object) listPartMenu.get(i).get("id");
				Object open = (Object) listPartMenu.get(i).get("open");
//				System.out.println(open);
				obj.put("name",name);
				obj.put("pId",pId);
				obj.put("id", id);
				obj.put("open",open);
				array.add(obj);
			}
			//array.add(obj);
			return array.toString();
//			return listPartMenu;
		}
		//增加checked：true
		for(int i = 0;i<listPartMenu.size();i++){
			String aloneMenuNo = listPartMenu.get(i).get("id").toString();
			for(int j=0;j<listMenuNo.size();j++){
				String menuNo = listMenuNo.get(j).get("menu_no").toString();
				if(menuNo.equals(aloneMenuNo)){
					listPartMenu.get(i).put("checked","true");
					break;
				}
			}
		}
		for(int i=0;i<listPartMenu.size();i++){
			JSONObject obj = new JSONObject();
			String name = (String) listPartMenu.get(i).get("name");
			Object pId = (Object) listPartMenu.get(i).get("pId");
			Object id = (Object) listPartMenu.get(i).get("id");
			Object open = (Object) listPartMenu.get(i).get("open");
			Object checked = (Object) listPartMenu.get(i).get("checked");
//			System.out.println(open);
			obj.put("name",name);
			obj.put("pId",pId);
			obj.put("id", id);
			obj.put("open",open);
			obj.put("checked",checked);
			array.add(obj);
		}
		return array.toString();
	}
	
}
